﻿using System.Linq;
using Xamarin.Forms;
using System.Collections.Generic;
using static Moven.ViewModels.ArticleWithBookmark;
using System;
using Moven.Data;

namespace Moven.ViewModels
{
	public partial class ArticlesViewModel
	{
		string PreviousSearchTerm { get; set; } = string.Empty;
		string _searchTerm = string.Empty;
		public string SearchTerm
		{
			get { return _searchTerm?? string.Empty; }
			set { SetProperty(ref _searchTerm, value);}
		}

		List<ArticleWithBookmark> _searchResults = new List<ArticleWithBookmark>();

		Command _searchCommand;
		public Command SearchCommand => _searchCommand ?? (_searchCommand = new Command(() =>
		{ SearchArticles(); UpdateTitle(); }));

		void InitSearch()
		{
			if (!IsSearchPage)
			{
				return;
			}
			Statics.ArticlesStore.ArticlesRefreshed += (sender, result) =>
			{
				if (result.Status == RefreshArticlesStatus.Failure)
				{
					return;
				}
				var newArticles = result.NewArticles;
				if (newArticles.IsNullOrEmpty())
				{
					return;
				}
				newArticles.OrderBy(x => x.Index).
				           ForEach(article => _allArticles.Insert(0, FromArticle(article)));
			};
		}

		void SearchArticles()
		{
			var searchTerm = SearchTerm.Trim();
			if (PreviousSearchTerm == searchTerm)
			{
				return;
			}
			PreviousSearchTerm = searchTerm;
			Articles.Clear();
			if (searchTerm.IsNullOrEmpty())
			{
				return;
			}

			var words = searchTerm.Split(new[] { ' ', ','}, StringSplitOptions.RemoveEmptyEntries).
			                      Distinct().ToArray(); 
			_searchResults = _allArticles.Where(
				x => words.Any(word => x.Title.Where(ch => ch != ' ').ConvertToString().Contains(word) ||
				               x.Tags.Contains(word))
			).ToList();
			_searchResults.Take(PageSize).ForEach(Articles.Add);
			HasMoreArticles = _searchResults.Count > PageSize;
		}

		void UpdateSearchTitle()
		{
			var searchTerm = SearchTerm?.Trim();
			if (searchTerm.IsNullOrEmpty())
			{
				Title = "搜索" + _allArticles.Count + "篇墨文";
			}
			else if (!Articles.Any())
			{
				Title = "未找到相关墨文";
			}
			else
			{
				Title = "找到" + _searchResults.Count + "篇\"" + searchTerm + "\"相关墨文";
			}
		}
	}
}
